package com.cheejee.goodscenter.service.impl;

import java.util.List;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

import org.springframework.stereotype.Service;

import com.carry.common.tool.StringTool;
import com.cheejee.goodscenter.dao.BrandMapper;
import com.cheejee.goodscenter.module.entity.Brand;
import com.cheejee.goodscenter.service.BrandService;
import com.cheejee.goodscenter.service.exception.DataNotExistException;
import com.cheejee.goodscenter.service.exception.DuplicateException;
import com.cheejee.goodscenter.validated.Check;
import com.cheejee.goodscenter.validated.InsertGroup;
import com.cheejee.goodscenter.validated.UpdateGroup;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.collection.CollectionUtil;

/**
 * 
 * @author CARRY
 * @Date 2020年10月21日下午3:02:25
 */
@Service
public class BrandServiceImpl implements BrandService {

	@Resource
	private BrandMapper brandMapper;


	@Override
	public Page<Brand> queryBrand(String name, String initial, int pageNum, int pageSize) {
		return PageHelper.startPage(pageNum, pageSize).doSelectPage(() -> brandMapper.seleteBySelective(name, initial));
	}
	
	@Override
	public Brand queryBrandById(@NotNull(message = "品牌id不能为空") Integer id) {
		
		return brandMapper.selectByPrimaryKey(id);
	}

	@Override
	@Check(message = "新增的品牌不能为空", group = InsertGroup.class)
	public int addBrand(Brand brand) {
		
		if(!CollectionUtil.isEmpty(brandMapper.seleteBySelective(brand.getName(), null))) {
			throw new DuplicateException("新增的品牌名称已存在");
		}
		
		brand.setInitial(StringTool.getInitial(brand.getName()));
		
		return brandMapper.insertSelective(brand);
	}

	@Override
	@Check(message = "更新的品牌不能为空", group = UpdateGroup.class)
	public int changeBrand(Brand brand) {
		
		checkExist(brand.getId());
		List<Brand> b = brandMapper.seleteBySelective(brand.getName(), null);
		
		if(!CollectionUtil.isEmpty(b) && b.get(0).getId() != brand.getId()) {
			throw new DuplicateException("修改的品牌名称已存在");
		}
		brand.setInitial(StringTool.getInitial(brand.getName()));
		
		return brandMapper.updateByPrimaryKeySelective(brand);
	}

	@Override
	public int deleteBrand(Integer... id) {
		return brandMapper.deleteById(id);
	}

	private void checkExist(Integer id) {
		if(brandMapper.selectByPrimaryKey(id) == null) {
			throw new DataNotExistException("品牌不存在");
		}
	}

}
